﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using Microsoft.TeamFoundation.Client;

namespace TFhisto
{
    /// <summary>
    /// Used to filter the changeset returned to build the file history
    /// </summary>
    public class SearchHelper
    {
        #region Private variables
        private Dictionary<SearchCriteria, Object> _searchCriterias = new Dictionary<SearchCriteria, object>();
        #endregion

        #region constructor
        public SearchHelper(Dictionary<SearchCriteria, Object> searchCriterias)
        {
            UpdateCriterias(searchCriterias);
        }
        #endregion

        #region Public methods
        public void UpdateCriterias(Dictionary<SearchCriteria, Object> searchCriterias)
        {
            //We check each criteria is unique
            Dictionary<SearchCriteria, Object> criterias = new Dictionary<SearchCriteria, object>();
            foreach (SearchCriteria criteria in searchCriterias.Keys)
            {
                if (!criterias.Keys.Contains(criteria))
                {
                    criterias.Add(criteria, searchCriterias[criteria]);
                }
            }
            _searchCriterias = criterias;
        }
        
        public int GetChangesetFrom()
        {
            return GetCriteria<int>(SearchCriteria.ChangesetFrom);
        }

        public int GetChangesetTo()
        {
            return GetCriteria<int>(SearchCriteria.ChangesetTo);
        }

        public DateTime GetDateFrom()
        {
            return GetCriteria<DateTime>(SearchCriteria.DateFrom);
        }

        public DateTime GetDateTo()
        {
            return GetCriteria<DateTime>(SearchCriteria.DateTo);
        }
        #endregion

        #region Private methods
        private T GetCriteria<T>(SearchCriteria criteria) where T : new()
        {
            T result = new T();

            if (_searchCriterias.Keys.Contains(criteria))
            {
                if (_searchCriterias[criteria] != null && _searchCriterias[criteria].GetType() == typeof(T))
                {
                    result = (T)_searchCriterias[criteria];
                }
            }
            return result;
        }
        #endregion
    }

    public enum SearchCriteria
    {
        DateFrom,
        DateTo,
        ChangesetFrom,
        ChangesetTo
    }
}